﻿// http://www.dijksterhuis.org/simple-class-to-submit-post-a-web-form-from-csharp/
using System;
using System.Net;
using System.Web;
using System.IO;
using System.Collections;

namespace Algobox.JuicyLib.Net
{
    public class WebPostRequest : IDisposable
    {
        WebRequest m_Request;
        HttpWebResponse m_Response;
        ArrayList m_Data;

        public WebRequest Request { get { return m_Request; } }
        public HttpWebResponse Response { get { return m_Response; } }

        public string Referer
        {
            set
            {
                //m_Request.Headers.Add("Referer", value);
                m_Request.Headers["Referer"] = value;
            }        
        }

        public string Cookie
        {
            set
            {
                m_Request.Headers["Cookie"] = value;
            }
        }

        public WebPostRequest(string url)
        {
            m_Request = WebRequest.Create(url);
            m_Request.Method = "POST";
            m_Data = new ArrayList();
        }

        public WebPostRequest(Uri url)
        {
            m_Request = WebRequest.Create(url);
            m_Request.Method = "POST";
            m_Data = new ArrayList();
        }

        public void Add(string key, string value)
        {
            m_Data.Add(String.Format("{0}={1}", key, HttpUtility.UrlEncode(value)));
        }

        public string GetResponse()
        {
            // Set the encoding type
            m_Request.ContentType = "application/x-www-form-urlencoded";

            // Build a string containing all the parameters
            string Parameters = String.Join("&", (String[])m_Data.ToArray(typeof(string)));
            m_Request.ContentLength = Parameters.Length;

            // We write the parameters into the request
            StreamWriter sw = new StreamWriter(m_Request.GetRequestStream());
            sw.Write(Parameters);
            sw.Close();

            // Execute the query
            m_Response = (HttpWebResponse)m_Request.GetResponse();
            StreamReader sr = new StreamReader(m_Response.GetResponseStream());
            return sr.ReadToEnd();
        }


        #region IDisposable Members

        public void Dispose()
        {
            m_Request = null;
            m_Response = null;
        }

        #endregion
    }
}
